package com.project.erp.service.system.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.project.erp.common.utils.Page;
import com.project.erp.dao.system.RoleDao;
import com.project.erp.dao.system.UserDao;
import com.project.erp.model.system.Role;
import com.project.erp.model.system.User;
import com.project.erp.service.system.RoleService;

@Service
@Transactional
public class RoleServiceImpl implements RoleService{

	@Autowired
	private RoleDao roleDao;
	
	@Autowired
	private UserDao userDao;
	
	//只读事务，可以提高效率
	@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)
	@Override
	public List<Role> getAllRoles() {
		return roleDao.getAll();
	}

	//只读事务，可以提高效率
	@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)
	@Override
	public Page<Role> getRolePageBySearch(Page<Role> page, Role role) {
		return roleDao.getRolePageBySearch(page, role);
	}
	
	@Transactional(rollbackFor=Exception.class)
	@Override
	public void saveRole(Role role){
		roleDao.save(role);
	}
	
	@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)
	@Override
	public Role getRoleById(Long roleId){
		return roleDao.get(roleId);
	}
	
	@Transactional(rollbackFor=Exception.class)
	@Override
	public void editRole(Role role){
		roleDao.save(role);
	}
	
	@Transactional(rollbackFor=Exception.class)
	@Override
	public boolean delRole(String[] roleIds){
		if(null == roleIds || roleIds.length == 0){
			return false;
		}
		List<Long> ids = new ArrayList<Long>();
		for (String roleId : roleIds) {
			ids.add(Long.valueOf(roleId));
		}
		//查询角色是否被用户引用,有引用不给删除
		List<User> users = userDao.queryUserByCriteria(ids);
		if(null != users && users.size() > 0){
			return false;
		}
		//删除角色信息
		String hql = "delete from Role r where r.id in(:ids)";
		Map<String,Object> params = new HashMap<String,Object>();
		params.put("ids", ids);
		roleDao.batchExecute(hql,params);
		return true;
	}
}
